﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SqlAutoRun
{
    class Program
    {
        static void Main(string[] args)
        {
            //string path = args[0];
            //string newpath = args[1]; 
            //string ip = args[2];
            //string databaseName = args[3]; 
            //string user = args[4];
            //string pwd = args[5]; 

            string path = @"";//原文件夹
            string newPath = $@"D:\TempSqlAutoRun\{DateTime.Now.ToString("yyyyMMddhhmmss")}";//转换编码格式后的文件夹

            string ip = ""; //
            string databaseName = "";
            string user = "";
            string pwd = "";


            List<string> sqlOrginPathList = GetSqlOrginPath(path);
            foreach (var item in sqlOrginPathList)
            {
                ChangeSqlEncoding($"{path}\\{item}", item, newPath);
            }

            Dictionary<string, int> sqlFilePath = GetSqlFilePath(newPath);
            OSQLHepler osqlHepler = new OSQLHepler($"{ip}", databaseName, user, pwd);

            foreach (var item in sqlFilePath)
            {
                Console.WriteLine($"排序:{item.Value}");
                Console.WriteLine($"获取文件名:{item.Key}");
                osqlHepler.ExcutesqlFile(item.Key);
                Console.WriteLine("========================================================================================================================\n");
            }


            Console.ReadKey();
        }

        /// <summary>
        /// 转换sql编码格式并存储 utf-8 to gb2312
        /// </summary>
        /// <param name="sqlPath">需要转换的sql文件路径</param>
        /// <param name="sqlName">需要转换的sql文件名</param>
        /// <param name="newPath">转换编码格式后的文件夹</param>
        /// <returns></returns>
        public static void ChangeSqlEncoding(string sqlPath, string sqlName, string newPath)
        {
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            //新文件路径
            var fullPath = Path.Combine(newPath, sqlName);

            //获取原始文件的编码格式
            Encoding sqlEncoding = FileEncoding.GetType(sqlPath);
            //如果是utf-8 转为gb2312 否则直接复制
            if (sqlEncoding.BodyName == "utf-8")
            {
             
                //读取的sql脚本
                string text = System.IO.File.ReadAllText(sqlPath);
                //根据新文件路径 创建文件
                //写入文件
                using (StreamWriter sw = new StreamWriter(fullPath, false, System.Text.Encoding.GetEncoding("gb2312")))
                {
                    sw.WriteLine(text);
                }
            }
            else
            {
                File.Copy(sqlPath, fullPath);
            }


        }


        //获取所有原始文件路径
        public static List<string> GetSqlOrginPath(string path)
        {
            List<string> pathList = new List<string>();
            DirectoryInfo folder = new DirectoryInfo(path);
            foreach (FileInfo file in folder.GetFiles("*.sql"))
            {
                pathList.Add(file.Name);
            }
            return pathList;
        }


        //获取sql文件路径并处理
        public static Dictionary<string, int> GetSqlFilePath(string path)
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            try
            { //排序 CreateTables.sql  AlterTables.sql  SysData.sql 其他sql
                DirectoryInfo folder = new DirectoryInfo(path);
                int i = 4;
                foreach (FileInfo file in folder.GetFiles("*.sql"))
                {
                    if (file.FullName.Contains("CreateTables.sql"))
                    {
                        dictionary.Add(file.FullName, 1);
                    }
                    else if (file.FullName.Contains("AlterTables.sql"))
                    {
                        dictionary.Add(file.FullName, 2);
                    }
                    else if (file.FullName.Contains("SysData.sql"))
                    {
                        dictionary.Add(file.FullName, 3);
                    }
                    else
                    {
                        dictionary.Add(file.FullName, i++);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("获取sql文件失败!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                Console.WriteLine(e);
                throw;
            }

            return dictionary.OrderBy(o => o.Value).ToDictionary(p => p.Key, o => o.Value); ;
        }
        /// <summary>
        /// utf-8转gb2312
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UTF8ToGB2312(string str)
        {
            try
            {
                Encoding utf8 = Encoding.GetEncoding(65001);
                Encoding gb2312 = Encoding.GetEncoding("gb2312");//Encoding.Default ,936
                byte[] temp = utf8.GetBytes(str);
                byte[] temp1 = Encoding.Convert(utf8, gb2312, temp);
                string result = gb2312.GetString(temp1);
                return result;
            }
            catch (Exception ex)//(UnsupportedEncodingException ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }
    }
}
